/*
 * @Author: 梦付千秋星垂野 465943794@qq.com
 * @Date: 2022-09-30 10:15:12
 * @LastEditors: 梦付千秋星垂野 465943794@qq.com
 * @LastEditTime: 2022-10-24 15:39:04
 * @FilePath: /practise--chat-app-react-nodejs/pubilc/src/pages/Chat.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React from 'react'
import  { useEffect, useState, useRef } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { io } from "socket.io-client";
import { allUsersRoute, host } from "../utils/APIRoutes";
import styled from "styled-components";
import ChatContainer from "../components/ChatContainer";
import Contacts from "../components/Contacts";
import Welcome from "../components/Welcome";
export default function Chat() {
  const navigate = useNavigate();
  const socket = useRef();
  const [contacts, setContacts] = useState([]);
  const [currentChat, setCurrentChat] = useState(undefined);
  const [currentUser, setCurrentUser] = useState(undefined);
  useEffect(()=>{
    const fetchData=async () => {
    if (!localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)) {
      navigate("/login");
    } else {
      setCurrentUser(
        await JSON.parse(
          localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)
        )
      );
    }
  }
  fetchData()
}, []);
  useEffect(() => {
  if (currentUser) {
    socket.current = io(host);
    socket.current.emit("add-user", currentUser._id);
  }
  }, [currentUser]);
  useEffect(()=>{
  const fetchData=async () => {
    if (currentUser) {
      if (currentUser.isAvatarImageSet) {
        const data = await axios.get(`${allUsersRoute}/${currentUser._id}`);
        setContacts(data.data);
      } else {
        navigate("/setAvatar");
      }
    }
  }
  fetchData()
  }
  , [currentUser]);
  const handleChatChange = (chat) => {
    setCurrentChat(chat);
  };
  return (
   <>
   <Container>
   <div className="container">
   <Contacts contacts={contacts} changeChat={handleChatChange} />
   {currentChat === undefined ? (
            <Welcome />
          ):(  <ChatContainer currentChat={currentChat} socket={socket}/>)
   }
   </div>
   
   </Container>

   </>
  )
}

const Container = styled.div`
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
align-items: center;
background-color: #131324;
.container {
  height: 85vh;
  width: 85vw;
  background-color: #00000076;
  display: grid;
  grid-template-columns: 25% 75%;
  @media screen and (min-width: 720px) and (max-width: 1080px) {
    grid-template-columns: 35% 65%;
  }
}
`;
